const fs  = require('fs')
const { get } = require('http')
const path = require('path')
const { json } = require('stream/consumers')

const url = path.join(__dirname,'./data.json')

//获取数据
// getData()
function getData(){
    fs.readFile(url,'utf-8',(err,data)=>{
        if(err) return console.log(err.message)
        //转换成对象
        let obj = JSON.parse(data)
        console.log(obj)
    })
}

//添加数据
addData({
    author:'邹华龙',
    bookname:'法外狂徒',
    publisher:'武汉人民出版社'
})
function addData(obj) {
    if(obj ===undefined)  return console.log('请输入内容')
    fs.readFile(url,'utf-8',(err,data)=>{
        if(err)  return console.log(err.message)
        let arr = JSON.parse(data)
    
        obj.id = arr[arr.length-1].id+1
        arr.push(obj)
        //写入文件
        fs.writeFile(url,JSON.stringify(arr),err=>{
            if(err) return console.log(err.message)
            console.log('恭喜你，添加图书成功！')
        })
    })
}